package com.meixiang.fragment.service;


import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.homes.service.ServiceDetailActivity;
import com.meixiang.adapter.service.ProjectAdapter;
import com.meixiang.entity.services.Index;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseFragment;
import com.meixiang.recyclerview.OnItemClick;
import com.meixiang.recyclerview.RecycleViewDivider;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 预约内的项目
 * xiejingwen
 */
public class ProjectFragment extends BaseFragment implements OnRefreshListener,OnLoadMoreListener {

    private View view;
    @Bind(R.id.swipe_target)
    RecyclerView swipeTarget;
    @Bind(R.id.refresh)
    SwipeToLoadLayout refresh;
    private Index index;
    private ProjectAdapter adapter;
    private String type="1"; //预约类型 1 预约 2 医美 3 医旅 4 基因检测
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater,container,savedInstanceState);
        view = inflater.inflate(R.layout.fragment_project, container, false);
        ButterKnife.bind(this, view);

        return view;
    }

    @Override
    protected void initTitle() {
    }

    @Override
    protected void initView() {
        refresh.setOnRefreshListener(this);
        refresh.setOnLoadMoreListener(this);
        //自动上拉
        swipeTarget.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (!ViewCompat.canScrollVertically(recyclerView, 1)) {
                        refresh.setLoadingMore(true);
                    }
                }
            }
        });
        swipeTarget.setLayoutManager(new LinearLayoutManager(getActivity()));
        swipeTarget.addItemDecoration(new RecycleViewDivider(getActivity(), RecycleViewDivider.HORIZONTAL_LIST));
        adapter=new ProjectAdapter(this);
        adapter.setOnItemClickListener(new OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                Bundle bundle=new Bundle();
                bundle.putString("goodsId",adapter.data.get(position).getGoodsId());
                startActivity(bundle,ServiceDetailActivity.class);
            }
        });
        swipeTarget.setAdapter(adapter);
    }

    @Override
    protected void setData() {
        showLoading();
        getData(1,type,true);
    }

    /**
     * @param current 当前页数
     * @param type 预约类型 1 预约 2 医美 3 医旅 4 基因检测
     * @param isDownPull 是否下拉（下拉清空，上拉不清空）
     */
    private void getData(final int current, final String type, final boolean isDownPull){
        HttpParams params=new HttpParams();
        params.put("appoitmentType", type);
        params.put("pageNo", current + "");
        HttpUtils.post(Config.INDEX_LIST, params, new HttpCallBack(getActivity()) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {

                if (isDownPull) {
                    adapter.clearData();
                }
                index=AbJsonUtil.fromJson(result.toString(),Index.class);
                if (index.getList()!=null&&index.getList().size()>0){
                    removeStatus();
                    adapter.addData(index.getList());
                }else{
                    showNoData("暂无数据");
                }
            }

            @Override
            public void onError(String code, String message) {
                //AbToastUtil.showToast(activity, message);
                showNoData(message, "重新加载", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showLoading();
                        getData(current,type, true);
                    }
                });

            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                onComplete(refresh);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onLoadMore() {
        if (index.getTotalPage().equals(index.getPageNo())){
            AbToastUtil.showToast(getActivity(),"已没有更多数据");
            onComplete(refresh);
        }else{
            int pageNo=Integer.parseInt(index.getPageNo());
            pageNo++;
            getData(pageNo,type,false);
        }
    }

    @Override
    public void onRefresh() {
        getData(1,type,true);
    }

}
